<template>
  <!-- 腾讯云视频 -->
  <Top-Page class="tx-box">
    <TUICallKit
      :afterCalling="navBack"
      :beforeCalling="beforeCalling"
      :kickedOut="kickedOut"
      :statusChanged="statusChanged"
    />
    <cu-custom bgColor="bg-gradual-white-3" :isBack="true">
      <template #content>通话</template>
    </cu-custom>
    <view class="call-wrap">通信中......</view>
  </Top-Page>
</template>

<script lang="ts" setup>
import api from "@/api/index.js";

// #ifdef APP
import { sdkAppId, currentUserSig, TUICallKit, TIM, TUITIM, TUICallKitEvent } from "@/utils/trtc.js";

import { onLoad } from "@dcloudio/uni-app";

import { useMsgStore } from "@/store/message";
import pinia from "@/store/index";
import { onBeforeUnmount, ref } from "vue";

const msgStore = useMsgStore(pinia);

const memberLists = msgStore.memberList;
const userInfo = uni.getStorageSync("userInfo");
const user_id = String(userInfo.user_id);
let roomID = Number(userInfo.user_id);

const query: any = {};

onLoad((params) => {
  Object.assign(query, params);
  if (params.status === "call") {
    roomID = Number(userInfo.user_id);
    if (!memberLists.length) {
      uni.showToast({
        title: "通话异常，请重新拨打",
        icon: "none",
      });

      uni.reLaunch({
        url: "/pages/index/index",
      });

      return;
    }
  } else {
    roomID = Number(query.toContactId);
  }

  //登录
  setSelfInfo();
});

TUICallKitEvent.addEventListener("onError", handleError);
TUICallKitEvent.addEventListener("onCallEnd", onCallEnd);
TUICallKitEvent.addEventListener("onCallCancelled", onCallCancelled);

onBeforeUnmount(() => {
  console.log("onBeforeUnmount页面销毁前");
  msgCallback("hangup", "");
  TUICallKitEvent.removeEventListener("onError", handleError);
  TUICallKitEvent.removeEventListener("onCallEnd", onCallEnd);
  TUICallKitEvent.removeEventListener("onCallCancelled", onCallCancelled);
});

//错误回调
function handleError(res: any) {
  console.log("错误回调", res);
  navBack();
}

//通话结束
function onCallEnd(res: any) {
  console.log("通话结束", res);
  navBack();
}

//通话主叫取消、被叫超时、拒接等，涉及多个场景
function onCallCancelled(res: any) {
  console.log("通话主叫取消、被叫超时、拒接等，涉及多个场景", res);
  navBack();
}

//设置用户昵称、头像。用户昵称不能超过500字节，用户头像必须是URL格式。
function setSelfInfo() {
  const options = {
    nickName: userInfo.realname,
    avatar: userInfo.avatar,
  };

  TUICallKit.setSelfInfo(options, (res) => {
    if (res.code === 0) {
      console.log("设置用户信息成功");

      query.status === "call"
        ? //发起通话
          groupCall()
        : //加入群组通话
          join();
    } else {
      console.log(`setSelfInfo failed, error message = ${res.msg}`);
    }
  });
}

//发起群组通话
async function groupCall() {
  const userIDList = memberLists.map((item: { userID: any }) => String(item.userID));
  const groupID = await createGroupID();

  const options = {
    groupID: groupID,
    userIDList: userIDList,
    callMediaType: Number(query.type),
    CallParams: {
      roomID: userInfo.user_id,
    },
  };

  console.log("准备呼叫");
  // ws
  await msgCallback("calling", groupID);

  console.log("呼叫参数", options);

  TUICallKit.groupCall(options, (res) => {
    if (res.code === 0) {
      console.log("call success");
    } else {
      console.log(`call failed, error message = ${res.msg}`);
    }
  });
}

//加入群组通话
function join() {
  const options = {
    callId: roomID,
  };

  TUICallKit.join(options, (res) => {
    if (res.code === 0) {
      console.log("join success");
    } else {
      console.log(`join failed, error message = ${res.msg}`);
      navBack();
    }
  });
}

async function msgCallback(event: string, groupID: string) {
  const call_user_id = memberLists.map((item: { userID: number }) => item.userID);

  await api.msgApi
    .sendToGroupMsg({
      event: event,
      call_user_id: call_user_id,
      type: 2,
      groupID: groupID,
      roomID: userInfo.user_id,
      msg_id: query.msg_id,
      status: event === "calling" ? 1 : 0,
      code: "",
      callTime: "",
      sdp: "",
      iceCandidate: "",
      toContactId: String(query.id),
    })
    .then((res) => {
      console.log(res, "拨打");
      if (res.data.extends?.code == 907) {
        uni.showToast({
          title: "对方不在线",
          icon: "none",
        });
        navBack();
      }
    });
}

// 获取需要邀请的成员
const getMissingMembers = async (groupID: string) => {
  const currentMembers = await TUITIM.getGroupMemberList({
    groupID: groupID,
  });
  return memberLists
    .filter((item: { userID: number }) => !currentMembers.data.memberList.some((m) => m.userID === String(item.userID)))
    .map((item: { userID: number }) => String(item.userID));
};

//退出
const kickedOut = (e) => {
  navBack();
};

const beforeCalling = (e) => {
  console.log(e, "拨打电话前与收到通话邀请前会执行此函数");
};

const statusChanged = (e) => {
  console.log("----------通话状态发生变化-----------");
  console.log(e);
  if (e.newStatus === "idle") {
    console.log("挂断");
  } else if (e.newStatus === "calling-group") {
    console.log("正在群组呼叫");
  } else if (e.newStatus === "calling-group-video") {
    console.log("正在群组视频通话");
  }
};

async function createGroupID() {
  let groupID = userInfo.groupID ?? "";
  if (groupID) {
    return groupID;
  } else {
    const memberList: any[] = memberLists.map((item: any) => ({ userID: String(item.userID) }));

    const res = await TUITIM.createGroup({
      type: TIM.TYPES.GRP_PUBLIC,
      name: "群视频",
      memberList,
      joinOption: TIM.TYPES.JOIN_OPTIONS_FREE_ACCESS,
    });

    groupID = res.data.group.groupID;

    //记住创建的groupID
    userInfo["groupID"] = groupID;
    uni.setStorageSync("userInfo", userInfo);

    return groupID;
  }
}

const navBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};
// #endif
</script>

<style lang="scss" scoped>
.tx-box {
  width: 750rpx;
  height: 100vh;

  .call-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
}
</style>
